package encome.work.controller;


import cn.hutool.core.date.DateTime;
import com.alibaba.fastjson.JSON;

import encome.work.dao.Message;
import encome.work.service.MessageSevice;
import encome.work.service.StaffService;
import encome.work.utils.WebSocketUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Date;

@Component
@ServerEndpoint("/tree_hole/chat/{id}")
public class TreeHoleWebsocket {
    //由于是websocket,spring识别不了其为controller层,所以@Resource注入Service不成功
    private static MessageSevice messageService;
    private static StaffService staffService;

    @Autowired
    public void setStaffService(StaffService staffService) {
        this.staffService = staffService;
    }

    @Autowired
    public void setMessageService(MessageSevice messageService) {
        this.messageService = messageService;
    }

    @OnOpen
    public void onOpen(Session session, @PathParam("id") String id) {
        if (Long.valueOf(id) < 0 && staffService.isStaff(-Long.valueOf(id))) {
            WebSocketUtil.addSession(id, true, session);
        } else {
            WebSocketUtil.addSession(id, false, session);
        }
    }

    //前端应该发送Message Json化后的字符串
    @OnMessage
    public void onMessage(String message) {
        //心跳检测
//        if(message.equals("pong"))return;

        Message newMessage = JSON.parseObject(message, Message.class);
        newMessage.setTime(DateTime.now());
        //群发
        if (WebSocketUtil.isOnline(String.valueOf(newMessage.getTo()))) {
            newMessage.setStatus(0);
            if (newMessage.getTo() != 0) {
                WebSocketUtil.sendTo(String.valueOf(newMessage.getTo()), message);
            } else {
                WebSocketUtil.broadcastToOnlineStaff(message);
            }
        } else {
            newMessage.setStatus(1);
            messageService.add(newMessage);
        }
    }

    @OnClose
    public void onClose(Session session, @PathParam("id") String id) {
        WebSocketUtil.removeSession(id, session);
    }

}

